﻿from django.shortcuts import render, HttpResponse
from django.http import JsonResponse


# Create your views here.
def index(request):
    '''首页

    准备工作
    '''
    markdown = """# Request对象与Response对象

链接示例 | 说明
---|---
[request](/7/request) | request对象
[response](/7/response) | response对象
[json](/7/json) | json对象

## Request对象

* 视图

```python
def request_view(request):
    context = {
        'title': 'Request',
        'META': request.META,
        'user': request.user,
        'headers': request.headers,
    }
    return render(request, '07_1.html', context)
```

* 模板

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{ request }}</title>
</head>
<body>
    <h2>headers</h2>
    {{ headers }}
    <h2>user</h2>
    {{ user }}
    <h2>META</h2>
    {{ META }}
</body>
</html>
```

* 路由

```python
urlpatterns = [
    ...
    path('request/', views.request_view, name='request'),
]
```

## Response对象

* 视图

```python
from django.http import JsonResponse

def response_view(request):
    return HttpResponse(
        content='HttpResponse',
        content_type='text/plain',
        status=500
    )

def json_view(request):
    return JsonResponse(
        {
            'name': '李铁牛',
            'age': '18'
        },
        json_dumps_params={'ensure_ascii': False}
    )
```

* 路由

```python
urlpatterns = [
    ...
    path('response/', views.response_view, name='response'),
    path('json/', views.json_view, name='json'),
]
```

"""
    context = {
        'title': 'Home',
        'markdown': markdown,
    }
    return render(request, 'marked.html', context)


def request_view(request):
    context = {
        'title': 'Request',
        'META': request.META,
        'user': request.user,
        'headers': request.headers,
    }
    return render(request, '07_1.html', context)


def response_view(request):
    return HttpResponse(
        content='HttpResponse',
        content_type='text/plain',
        status=500
    )


def json_view(request):
    return JsonResponse(
        {
            'name': '李铁牛',
            'age': '18'
        },
        json_dumps_params={'ensure_ascii': False}
    )
